package web;

import service.RegisterService;
import service.UserAddService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * @author fire'ge
 */
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获取连接

            //检查用户名是否存在，存在则返回该用户名已注册
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
        String checkUsername = null;
        try {
            checkUsername = RegisterService.checkUsername(username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (checkUsername != null){

                request.getRequestDispatcher("/html/register.html").forward(request,response);
            }
            else {

            boolean update = false;
            try {
                update = UserAddService.addUserList(username, password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if(update){
                    writer.write("注册成功");
                    request.getRequestDispatcher("/index.jsp").forward(request,response);
                }
                else {
                        writer.write("注册失败，请重新注册");
                    request.getRequestDispatcher("/html/register.html").forward(request,response);

                }
            }
    }
@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
